from flask import Flask, render_template, request, redirect, url_for, session, jsonify, flash
from datetime import datetime, timedelta
import mysql.connector
import os

app = Flask(__name__)
app.secret_key = 'your_secret_key'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'docx'}

# MySQL数据库配置
try:
    db = mysql.connector.connect(
        host="152.136.49.229",
        user="yuyu",
        password="123456",
        database="userinfo",
        charset='utf8mb4'
    )
    print("数据库连接成功")
except mysql.connector.Error as err:
    print(f"数据库连接失败: {err}")

# 登录
@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        password = request.form['password']

        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s AND role=%s", (username, password, user_type))
        user = cursor.fetchone()

        if user:
            session['username'] = username
            session['user_type'] = user_type
            if user_type == 'student':
                return redirect(url_for('student_dashboard', username=username))
            elif user_type == 'teacher':
                return redirect(url_for('teacher_dashboard', username=username))
            elif user_type == 'parent':
                return redirect(url_for('parent_dashboard', username=username))
        else:
            flash('登录失败，用户名或密码错误！', 'danger')
            return redirect(url_for('login'))

    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        id = request.form['id']
        password = request.form['password']

        print(f"尝试注册用户: {username}，类型: {user_type}")

        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT * FROM users WHERE username=%s", (username,))
        existing_user = cursor.fetchone()

        if existing_user:
            print("用户名已存在")
            flash('用户名已存在，请选择其他用户名。', 'danger')
            return redirect(url_for('register'))

        try:
            cursor.execute("INSERT INTO users (username, password, id, role) VALUES (%s, %s, %s, %s)",
                           (username, password, id, user_type))
            db.commit()
            print("用户注册成功")
            flash('注册成功！', 'success')
        except mysql.connector.Error as err:
            print(f"插入用户数据失败: {err}")
            flash(f'注册失败: {err}', 'danger')
            return redirect(url_for('register'))

        return redirect(url_for('register_success'))

    return render_template('register.html')

@app.route('/register_success')
def register_success():
    return render_template('register_success.html')

@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        new_password = request.form['new_password']

        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT * FROM users WHERE username=%s AND role=%s", (username, user_type))
        user = cursor.fetchone()

        if user:
            cursor.execute("UPDATE users SET password=%s WHERE username=%s AND role=%s",
                           (new_password, username, user_type))
            db.commit()
            flash('密码重置成功！', 'success')
            return redirect(url_for('password_reset_success'))
        else:
            flash('用户名不存在。', 'danger')
            return redirect(url_for('forgot_password'))

    return render_template('forgot_password.html')

@app.route('/password_reset_success')
def password_reset_success():
    return render_template('password_reset_success.html')

# 学生页面
@app.route('/student_dashboard/<username>', methods=['GET', 'POST'])
def student_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    cursor = db.cursor(dictionary=True)

    if request.method == 'POST':
        class_name = request.form['class_name']

        cursor.execute("UPDATE users SET class=%s WHERE username=%s AND role='student'", (class_name, username))
        db.commit()

        cursor.execute("SELECT * FROM classes WHERE class_name=%s", (class_name,))
        class_data = cursor.fetchone()

        if not class_data:
            cursor.execute("INSERT INTO classes (class_name) VALUES (%s)", (class_name,))
            db.commit()

        cursor.execute("INSERT INTO student_classes (student_id, class_name) VALUES ((SELECT id FROM users WHERE username=%s), %s)",
                       (username, class_name))
        db.commit()

        flash(f'成功加入班级 {class_name}！', 'success')
        return redirect(url_for('student_class', username=username, class_name=class_name))

    cursor.execute("SELECT class FROM users WHERE username=%s AND role='student'", (username,))
    student_class = cursor.fetchone()
    student_class_name = student_class['class'] if student_class else None

    return render_template('student_dashboard.html', username=username, class_name=student_class_name)

# 学生选择加入考试页面
@app.route('/student_class/<username>/<class_name>', methods=['GET', 'POST'])
def student_class(username, class_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    cursor = db.cursor(dictionary=True)

    if request.method == 'POST':
        exam_name = request.form.get('exam_name')
        cursor.execute("SELECT * FROM exams WHERE exam_name=%s AND class_name=%s", (exam_name, class_name))
        exam = cursor.fetchone()

        if exam:
            cursor.execute("SELECT * FROM exam_participants WHERE exam_name=%s AND student_id=(SELECT id FROM users WHERE username=%s)",
                           (exam_name, username))
            participant = cursor.fetchone()

            if participant:
                flash('你已经参加过此考试，不能再次加入。', 'danger')
                return redirect(url_for('student_class', username=username, class_name=class_name))

            cursor.execute("INSERT INTO exam_participants (exam_name, student_id) VALUES (%s, (SELECT id FROM users WHERE username=%s))",
                           (exam_name, username))
            db.commit()

            session['exam'] = exam
            session['exam_start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
            return redirect(url_for('exam_page', class_name=class_name, exam_name=exam_name))

        flash('没有找到该考试。', 'danger')
        return redirect(url_for('student_class', username=username, class_name=class_name))

    cursor.execute("SELECT exam_name FROM exams WHERE class_name=%s", (class_name,))
    exam_list = cursor.fetchall()
    return render_template('student_class.html', username=username, class_name=class_name, exams=exam_list)

# 考试页面
@app.route('/exam/<class_name>/<exam_name>', methods=['GET', 'POST'])
def exam_page(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    cursor = db.cursor(dictionary=True)
    cursor.execute("SELECT * FROM exams WHERE exam_name=%s AND class_name=%s", (exam_name, class_name))
    exam = cursor.fetchone()

    if exam:
        remaining_time = exam['end_time'] - datetime.now()
        if remaining_time.total_seconds() <= 0:
            flash('考试时间已到，系统已自动提交。', 'warning')
            return redirect(url_for('exam_finished', class_name=class_name, exam_name=exam_name))

        remaining_seconds = int(remaining_time.total_seconds())

        return render_template('exam.html', remaining_time=remaining_seconds, class_name=class_name, exam_name=exam_name)

    flash('没有找到考试信息。', 'danger')
    return redirect(url_for('student_class', username=session.get('username'), class_name=class_name))

# 新增的考试完成页面
@app.route('/exam_finished/<class_name>/<exam_name>', methods=['GET'])
def exam_finished(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name, username=session['username'])

@app.route('/submit_exam/<class_name>/<exam_name>', methods=['POST'])
def submit_exam(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    try:
        exam_start_time_str = session.get('exam_start_time')
        if not exam_start_time_str:
            raise ValueError("考试开始时间未找到")

        exam_start_time = datetime.strptime(exam_start_time_str, '%Y-%m-%d %H:%M:%S.%f')
        elapsed_time = datetime.now() - exam_start_time
        elapsed_seconds = int(elapsed_time.total_seconds())

        session.pop('exam', None)
        session.pop('exam_start_time', None)

        return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name,
                               elapsed_seconds=elapsed_seconds, username=session['username'])
    except Exception as e:
        return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name, error=str(e),
                               username=session['username'])

# 老师页面
@app.route('/teacher_dashboard/<username>', methods=['GET', 'POST'])
def teacher_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        if 'add_exam' in request.form:
            return redirect(url_for('set_exam_time', username=username))

    return render_template('teacher_dashboard.html', username=username)

@app.route('/manage_class/<username>', methods=['GET', 'POST'])
def manage_class(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        class_name = request.form.get('class_name', '')
        if not class_name:
            flash('班级名称不能为空', 'danger')
            return redirect(url_for('manage_class', username=username))

        return redirect(url_for('class_management', class_name=class_name))

    return render_template('teacher_dashboard.html', username=username)

@app.route('/class_management/<class_name>', methods=['GET'])
def class_management(class_name):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    cursor = db.cursor(dictionary=True)
    cursor.execute("SELECT username FROM users WHERE class=%s AND role='student'", (class_name,))
    students = cursor.fetchall()

    cursor.execute("SELECT exam_name FROM exams WHERE class_name=%s", (class_name,))
    ongoing_exams = cursor.fetchall()

    return render_template('class_management.html', class_name=class_name, students=students,
                           ongoing_exams=ongoing_exams)

# 设置考试时间页面
@app.route('/set_exam_time/<username>', methods=['GET', 'POST'])
def set_exam_time(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    cursor = db.cursor(dictionary=True)

    if request.method == 'POST':
        exam_name = request.form.get('exam_name', '')
        class_name = request.form.get('class_name', '')
        exam_duration = request.form.get('exam_duration', '')
        if not exam_name or not class_name or not exam_duration:
            flash('考试名称、班级名称和考试时长不能为空', 'danger')
            return redirect(url_for('set_exam_time', username=username))

        end_time = datetime.now() + timedelta(minutes=int(exam_duration))
        cursor.execute("INSERT INTO exams (exam_name, class_name, start_time, end_time) VALUES (%s, %s, %s, %s)",
                       (exam_name, class_name, datetime.now(), end_time))
        db.commit()

        flash(f'考试 {exam_name} 设置成功！', 'success')
        return redirect(url_for('class_management', class_name=class_name))

    cursor.execute("SELECT class_name FROM classes")
    class_list = cursor.fetchall()

    return render_template('set_exam_time.html', username=username, classes=class_list)

# 家长页面
@app.route('/parent_dashboard/<username>')
def parent_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'parent':
        return redirect(url_for('login'))

    return render_template('parent_dashboard.html', username=username)

# 记录作弊行为
@app.route('/record_cheating', methods=['POST'])
def record_cheating():
    if 'username' in session:
        username = session['username']
        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT cheating_count FROM users WHERE username=%s", (username,))
        cheating_count = cursor.fetchone().get('cheating_count', 0)

        cheating_count += 1
        cursor.execute("UPDATE users SET cheating_count=%s WHERE username=%s", (cheating_count, username))
        db.commit()

        max_cheat_attempts = 2
        if cheating_count > max_cheat_attempts:
            return jsonify({'terminate': True})
        return jsonify({'terminate': False})
    return jsonify({'error': 'User not logged in'}), 401

# 终止考试
@app.route('/terminate_exam')
def terminate_exam():
    session.pop('exam', None)
    flash("由于检测到多次作弊行为，您的考试已被终止。", 'danger')
    return redirect(url_for('login'))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
